import { _decorator, Component, Node, Camera, Canvas, JsonAsset, resources, error, director } from 'cc';
import GlobalData from '../Config/GlobalData';
import { GlobalEnum } from '../Config/GlobalEnum';
import EventManager from '../Managers/EventManager';
import { EventTypes } from '../Managers/EventTypes';
import { AdvertSystem } from '../SystemAdvert/AdvertSystem';
import { AudioSystem } from '../SystemAudio/AudioSystem';
import { SDKSystem } from '../SystemSDK/SDKSystem';
import { StorageSystem } from '../SystemStorage/StorageSystem';
import { UIEnum } from '../SystemUI/UIEnum';
import { UISystem } from '../SystemUI/UISystem';
import { clog } from '../Tools/ColorLog';
import Loader from '../Tools/Loader';
import { Web } from '../Managers/TaskSDK/Web';
import { SDKTools } from '../Managers/TaskSDK/SDKTools';
import { MiniGameRunTimeMgr } from '../Managers/TaskSDK/小游戏运行时管理/MiniGameRunTimeMgr';
import { ADMgr } from '../Managers/TaskSDK/广告播放类/ADMgr';
import { WebDataProxy } from '../Managers/TaskSDK/数据代理类/WebDataProxy';
const { ccclass, property } = _decorator;

@ccclass('Init')
export class Init extends Component {
    protected uiLayer: Node = null;

    /**判断系统是否初始化完成 */
    private isSysInitFish = false;
    protected onLoad() {
        //
        GlobalData.set(GlobalEnum.GlobalDataType.Canvas, this.node);
        //
        GlobalData.set(GlobalEnum.GlobalDataType.CameraUI,
            this.node.getChildByName('CameraUI').getComponent(Camera));

        this.uiLayer = this.node.getChildByName('UILayer');

        this.initSystems();
    }

    //#region --------------------系统初始化-------------
    /**初始化各个系统 */
    protected async initSystems() {
        // hook uniSdk
        StorageSystem.init();
        AudioSystem.init();
        // if(!SDKTools.isKSGame){
        //     SDKSystem.init();
        // }
        UISystem.init(this.uiLayer);
        AdvertSystem.init(this.uiLayer);
        await Web.requireConfig(SDKTools.appid)
        console.log('SDKSystem.init', SDKTools.appid)
        SDKSystem.init();
        MiniGameRunTimeMgr.Init();
        MiniGameRunTimeMgr.ApiLoin().then((res) => {
            if (res) {
                Web.requireOpenID(SDKTools.appid, res);
            }
        });
    }

    protected update(dt) {
        this.checkSysInitState();
    }

    /**检测各个系统是否加载完成-防止异步*/
    protected checkSysInitState() {
        if (!this.isSysInitFish) {
            let isFinish = true;
            isFinish = isFinish && StorageSystem.isInitFinished;
            isFinish = isFinish && AudioSystem.isInitFinished;
            isFinish = isFinish && AdvertSystem.isInitFinished;
            isFinish = isFinish && SDKSystem.isInitFinished;
            isFinish = isFinish && UISystem.isInitFinished;
            this.isSysInitFish = isFinish;
            if (this.isSysInitFish) {
                this.enterGame();
            }
        }
    }
    //#endregion

    // #region -------------------进入游戏---------------
    protected async enterGame() {
        EventManager.emit(EventTypes.GameEvents.InitLoadFinished);
        clog.log('#进入游戏');

        // 定时器要释放
        let timeout: number = setTimeout(() => {
            clearTimeout(timeout);
            //广告
            UISystem.showUI(UIEnum.CustomAdUI);

            UISystem.showUI(UIEnum.HomeUI);

            setTimeout(() => {
                this.preLoadBound();
            }, 100);
        }, 100);

        setTimeout(() => {
            this.playAD();
        }, 1000);
    }


    private async playAD() {
        let sign_mode = WebDataProxy.inst.AdWebData.m_AdWebData?.sign_mode;
        console.error('sign_mode', sign_mode);
        if (sign_mode != 2) {
            //等于2才启动就后就强制放一个广告
            console.error('sign_mode等于2才启动就后就强制放一个广告');
            return;
        }
        console.error('启动后 播放 广告');
        let adDat = WebDataProxy.inst.AdWebData.GetPlayAd();
        let ad_unit = adDat.ad_unit;
        let dat = await ADMgr.PlayAd({
            adUnitId: ad_unit,
            showLoading: true,
            showError: true,
        })
        if (dat.res != 1) {
            // UISystem.showUI(UIEnum.TipUI, {
            //     tip: "激励视频需要完整播放才能获得奖励",
            //     showMode: "close",
            //     closeCallback: () => {
            //         director.emit(EventTypes.SDKEvents.ShowInsertAd)
            //     }
            // });
            return;
        }
    }

    // #endregion

    //#region --------------------预加载子包-------------
    /**预先加载的包名 非必须*/
    private preLoadBounds = ['AudioAssets', 'Game',];
    /**预先加载子包 */
    protected preLoadBound() {
        for (let i = 0, c = this.preLoadBounds.length; i < c; ++i) {
            Loader.loadBundle(this.preLoadBounds[i], null, false, false);
        }
    }
    // #endregion
}

